package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据统计的处理类。
 */
@Service
@Slf4j
public class ReportServiceImpl  implements ReportService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnOverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> days = new ArrayList<>();
        //对集合进行填充。
        List<Double> moneys = new ArrayList<>();
        LocalDate nowDay = begin;
        while (!nowDay.isAfter(end))
        {
            days.add(nowDay);
            nowDay = nowDay.plusDays(1);
        }
        //日期字符串
        String daysStr = StringUtils.join(days,",");
        //对日期进行遍历
        for (LocalDate day : days) {
            LocalDateTime dayStart = LocalDateTime.of(day, LocalTime.MIN);
            LocalDateTime dayEnd = LocalDateTime.of(day, LocalTime.MAX);

            Map map = new HashMap();
            // 状态已完成
            map.put("status", Orders.COMPLETED);
            map.put("begin",dayStart);
            map.put("end", dayEnd);

            Double turnover = orderMapper.sumByMap(map);
            // 如果查询的数据是null，则设置0.0
            turnover = turnover == null ? 0.0 : turnover;
            moneys.add(turnover);

        }

        return TurnoverReportVO.builder()
                .dateList(daysStr)
                .turnoverList(StringUtils.join(StringUtils.join(moneys),","))
                .build();
    }

    @Override
    /**
     * 用户数据统计
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> days = new ArrayList<>();
        //对集合进行填充。
        //日期集合进行填充
        LocalDate nowDay = begin;
        while (!nowDay.isAfter(end))
        {
            days.add(nowDay);
            nowDay = nowDay.plusDays(1);
        }
        //新增用户的集合
        List<Integer> newUsersNumber = new ArrayList<>();
        //总用户数的集合
        List<Integer> totalUsersNumber = new ArrayList<>();
        //新增用户数量集合 动态SQL进行查询
        //select count(id) from user where create_time > ? and end_time < ?
        for (LocalDate day : days) {
            LocalDateTime startTime = LocalDateTime.of(day, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(day, LocalTime.MAX);

            Integer totalUser = getUserCount(null,endTime);
            totalUsersNumber.add(totalUser);
            Integer newUser = getUserCount(startTime,endTime);
            newUsersNumber.add(newUser);
        }

        //总用户数统计

        return UserReportVO.builder()
                .dateList(StringUtils.join(days,","))
                .newUserList(StringUtils.join(newUsersNumber,","))
                .totalUserList(StringUtils.join(totalUsersNumber,","))
                .build();
    }

    /**
     * 订单信息的统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        //对日期集合进行填充
        List<LocalDate> days = new ArrayList<>();
        //对集合进行填充。
        //日期集合进行填充
        LocalDate nowDay = begin;
        while (!nowDay.isAfter(end))
        {
            days.add(nowDay);
            nowDay = nowDay.plusDays(1);
        }
        //对日期集合进行遍历，查询出每日的订单总数和有效订单数
        //SQL select count(id) where creat_time >= #{begin} create_time <=#{end}
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate day : days) {
            //对每日时间进行拼接
            LocalDateTime dayStartTime = LocalDateTime.of(day, LocalTime.MIN);
            LocalDateTime dayEndTime = LocalDateTime.of(day, LocalTime.MAX);
            Integer validOrder =  countOrders(dayStartTime,dayEndTime,5);
            Integer totalCountOrders = countOrders(dayStartTime, dayEndTime, null);
            orderCountList.add(totalCountOrders);
            validOrderCountList.add(validOrder);
        }
        //对订单的总数和有效订单总数进行处理
        Integer sum = orderCountList.stream().reduce(Integer::sum).get();
        Integer validTotal = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率
        Double orderCompletionRate = 0.0;
        if(sum != 0){
            orderCompletionRate = validTotal.doubleValue() / sum;
        }

        return OrderReportVO
                .builder()
                .totalOrderCount(sum)
                .validOrderCount(validTotal)
                .dateList(StringUtils.join(days,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    private Integer countOrders(LocalDateTime dayStartTime, LocalDateTime dayEndTime, Integer status) {
        Map map = new HashMap();
        map.put("begin",dayStartTime);
        map.put("end",dayEndTime);
        map.put("status",status);
        return orderMapper.countOrders(map);
    }

    private Integer  getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        return userMapper.userStatistics(map);
    }

    /**
     * 查询指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     * */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end){
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }


    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }




}
